package jmhtest;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

public class ByteBufTest {

    private static volatile ByteArrayThreadLocal byteThreadLocal = new ByteArrayThreadLocal();
    private static final int threads = 4;

    @Benchmark
    @Measurement(iterations = 2)
    @Threads(2)
    @Fork(0)
    @Warmup(iterations = 2, time = 2)
    public void poolDirectBuffer() {
        ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer(10);
        byteBuf.readBytes(byteThreadLocal.get(), 0, byteBuf.readableBytes());
        byteBuf.release();
    }

    @Benchmark
    @Measurement(iterations = 2)
    @Threads(2)
    @Fork(0)
    @Warmup(iterations = 2, time = 2)
    public void poolHeapBuffer() {
        ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.heapBuffer(10);
        byteBuf.readBytes(byteThreadLocal.get(), 0, byteBuf.readableBytes());
        byteBuf.release();
    }

    @Benchmark
    @Measurement(iterations = 2)
    @Threads(2)
    @Fork(0)
    @Warmup(iterations = 2, time = 2)
    public void unpoolDirectBuffer() {
        ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.directBuffer(10);
        byteBuf.readBytes(byteThreadLocal.get(), 0, byteBuf.readableBytes());
        byteBuf.release();
    }

    @Benchmark
    @Measurement(iterations = 2)
    @Threads(2)
    @Fork(0)
    @Warmup(iterations = 2, time = 2)
    public void unpoolHeapBuffer() {
        ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.heapBuffer(10);
        byteBuf.readBytes(byteThreadLocal.get(), 0, byteBuf.readableBytes());
        byteBuf.release();
    }

    public static void main(String[] args) {
        Options options = new OptionsBuilder().include(ByteBufTest.class.getSimpleName())
//                .addProfiler(GCProfiler.class)
                .build();
        try {
            new Runner(options).run();
        } catch (Exception e) {

        } finally {
        }
    }
}
